package com.rabbit.service.impl;

import cn.dev33.satoken.session.SaSession;
import com.rabbit.constant.DeviceType;
import com.rabbit.constant.ResultCodeEnum;
import com.rabbit.constant.SecurityConstant;
import com.rabbit.db.entity.Customer;
import com.rabbit.dto.LoginCustomerDTO;
import com.rabbit.exception.BusinessException;
import com.rabbit.mapper.CustomerMapper;
import com.rabbit.service.LoginService;
import com.rabbit.util.StpCustomerUtil;
import com.rabbit.vo.req.LoginReq;
import com.rabbit.vo.res.LoginRes;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Collections;

/**
 * @author zjw
 * @date 2022/6/22 15:40
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Resource
    private CustomerMapper customerMapper;

    @Override
    public LoginRes login(LoginReq loginReq) throws BusinessException {
        if (StringUtils.hasText(loginReq.getAgentCode())) {
            StpCustomerUtil.login(loginReq.getAgentCode(), DeviceType.APP);
            SaSession tokenSession = StpCustomerUtil.getTokenSession();
            LoginCustomerDTO loginCustomerDTO =  LoginCustomerDTO.builder().loginAccount(loginReq.getAgentCode())
                    .userName(loginReq.getPersonName()).build();
            tokenSession.set(SecurityConstant.LOGIN_CUSTOMER, loginCustomerDTO);
            tokenSession.set(SecurityConstant.LOGIN_ROLE, Collections.singletonList(SecurityConstant.APP_USER));
        } else {
            Customer customer = Customer.builder().name(loginReq.getName()).phone(loginReq.getPhone()).build();
            customer = customerMapper.selectOne(customer);
            if (customer != null) {
                StpCustomerUtil.login(customer.getCustomerId(), DeviceType.APP);
            } else {
                throw new BusinessException(ResultCodeEnum.USER_PASSWORD_ERROR);
            }
            SaSession tokenSession = StpCustomerUtil.getTokenSession();
            LoginCustomerDTO loginCustomerDTO =  LoginCustomerDTO.builder().loginAccount(customer.getPhone())
                    .userName(customer.getName()).build();
            tokenSession.set(SecurityConstant.LOGIN_CUSTOMER, loginCustomerDTO);
            tokenSession.set(SecurityConstant.LOGIN_ROLE, Collections.singletonList(SecurityConstant.APP_USER));
        }
        LoginRes loginRes = LoginRes.builder().build();
        loginRes.setToken(StpCustomerUtil.getTokenInfo().getTokenValue());
        return loginRes;
    }
}
